/* eslint-disable jsx-a11y/control-has-associated-label */
import React from 'react';
import ReactQuill from 'react-quill';

const QuillDeltaToHtmlConverter = require('quill-delta-to-html');
const htmlToRtf = require('html-to-rtf');

require("react-quill/dist/quill.snow.css");

const style = { height: 200 };


const importRtfFileToString = async () => {
    return new Promise((resolve, reject) => {
        let rtfTextContent = '';
        // 创建 input 元素
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.rtf';
        let isOpenFile = false;
        // 监听文件选择事件
        input.onchange = async (event) => {
            const file = event.target.files[0];
            if (file) {
                isOpenFile = true;
                // 读取文件内容
                const reader = new FileReader();
                reader.onload = (e) => {
                    rtfTextContent = e.target.result;
                    // 当文件读取完成后，调用 resolve 函数将结果传递出去
                    resolve(rtfTextContent);
                };
                reader.onerror = (error) => {
                    // 如果文件读取出现错误，调用 reject 函数
                    reject(error);
                };
                reader.readAsText(file);
            }
        };
        // 取消事件
        window.addEventListener(
            'focus',
            () => {
                setTimeout(() => {
                    if (!isOpenFile) {
                        // 取消逻辑处理
                        reject(new Error('User cancelled file selection'));
                    }
                }, 300);
            },
            { once: true }
        );

        // 触发文件选择对话框
        input.click();
    });
};

/* eslint-disable no-unreachable */
const RTFJS = require('rtf.js/dist/RTFJS.bundle');

function stringToArrayBuffer(string) {
    const buffer = new ArrayBuffer(string.length);
    const bufferView = new Uint8Array(buffer);
    for (let i = 0; i < string.length; i++) {
        bufferView[i] = string.charCodeAt(i);
    }
    return buffer;
}

const convertRtfHtmlString = async (rtfString) => {
    // eslint-disable-next-line no-useless-catch
    try {
        const doc = new RTFJS.Document(stringToArrayBuffer(rtfString));
        const meta = doc.metadata();
        const html = await doc.render();
        const d: any = {};
        d.html = html;
        d.meta = meta;
        return d;
    } catch(e) {
        throw e;
    }
};


class Page extends React.Component<any, any> {


  constructor(props) {
    super(props);

    this.state = {
        content: 'HELLO',
    };

  }

  toolbarId = `toolbar_${Math.random().toString(16).substring(2)}`;

  modules = {
    toolbar: {
        container: `#${this.toolbarId}`,
        handlers: {
        // insertStar: insertStar,
        },
    },
  };

  richText = React.createRef<any>();

  handleImportRtf = async () => {
    try{
        const rtfContentStr = await importRtfFileToString();

        // const rtfContentStr = '{\\rtf1\\ansi\\b Hello world!\\b0}';

        const deltaContent = await convertRtfHtmlString(rtfContentStr);

        const htmlStr = deltaContent.html.map(div => div.outerHTML).join('\n');

        console.log(htmlStr);

        // this.setState({content: htmlStr});
        const editor = this.richText.current.getEditor();

        if(!editor) {
            return;
        }

        editor.setText('');

        editor.clipboard.dangerouslyPasteHTML(0, htmlStr);

    } catch(e) {
        console.error(e);
    }
  };

  handleExportRtf = () => {
    const cfg = {};

    const editor = this.richText.current.getEditor();

    const deltaOps = editor.editor.delta.ops;
    const converter = new QuillDeltaToHtmlConverter(deltaOps, cfg);

    const html = converter.convert();

    // console.log(html);

    const rtfContent = htmlToRtf.convertHtmlToRtf(html);

    // from here on, works only on browser
    const blob = new Blob([rtfContent], {type: "application/rtf;charset=utf-8"});
    const blobURL=window.URL.createObjectURL(blob);

    const fileName='save.rtf';

    const tempLink = document.createElement('a');
          tempLink.style.display = 'none';
          tempLink.href = blobURL;
          const downloadName = decodeURIComponent(fileName);
          tempLink.setAttribute('download', downloadName);
          tempLink.download = downloadName;
          // alert(decodeURIComponent(fileName));
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank');
          }
          // 挂载a标签
          document.body.appendChild(tempLink);
          tempLink.click();
          setTimeout(() => {
            document.body.removeChild(tempLink);
            // 释放blob URL地址
            window.URL.revokeObjectURL(blobURL);
          }, 3000);

    // window.open(link);


  };

  renderCustomToolbar = ({id}) => {
    return (
      <div id={id}>
        <button type="button" className="ql-bold" />
        <button type="button" className="ql-italic" />
        <button type="button" className="ql-underline" />
        <button type="button" className="ql-strike" />
        <button type="button" className="ql-blockquote" />
        <button type="button" className="ql-list" value="ordered" />
        <button type="button" className="ql-list" value="bullet" />
        <button type="button" className="ql-image" />
        <button type="button" className="ql-link" />
        <select className="ql-color" />
        <button
          type="button"
          title='导入RTF'
          className="ql-import"
          style={{ outline: 'none' }}
          onClick={this.handleImportRtf}
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="feather feather-upload">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
            <polyline points="17 8 12 3 7 8" />
            <line x1="12" y1="3" x2="12" y2="15" />
          </svg>
        </button>
        <button
          type="button"
          className="ql-export"
          style={{ outline: 'none' }}
          title='导出RTF'
          onClick={this.handleExportRtf}
        >
          <svg style={{transform: 'rotate(180deg)'}} viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 22L12 10M12 10L8 14M12 10L16 14" stroke="black" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            <path d="M4 6H20" stroke="black" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
      </div>
    );
  };

  render() {
    return (
      <div>
        {this.renderCustomToolbar({id: this.toolbarId})}
        <div style={{ height: 200 }}>
          <ReactQuill
            modules={this.modules}
            // toolbar={this.renderCustomToolbar}
            defaultValue={this.state.content}
            ref={this.richText}
            style={style}
          />
        </div>
      </div>
    );
  }
}

export default Page;